// crud role
const cipher = require('util-cipher');
module.exports = app => {
  class systemService extends app.Service {
    async updateRoot(obj) {
      await this.ctx.model.rbac_role.update({
        name: 'admin',
      }, { $set: { auth: obj } });
      return;
    }
    async updateRole(roleName, obj) {
      await this.ctx.model.rbac_role.update({
        name: roleName,
      }, { $set: { auth: obj } });
      return;
    }
    async deleteRole(roleName) {
      await this.ctx.model.rbac_role.remove({ name: roleName });
      return;
    }
    async addRole(roleName, desc, authObj) {
      if (roleName === 'admin') return;
      const role = new this.ctx.model.rbac_role({
        name: roleName,
        desc,
        auth: authObj,
      });
      await role.save();
      return;
    }
    async userInit(userId) {
      const user = this.ctx.model.RbacUser.findOne({ _id: userId }).populate('roles');
      this.ctx.logger.info('user', user);
      const menu = {};
      const uri = {};
      const operations = {};
      user.roles.forEach(roles => {
        roles.auth.menu.forEach(m => {
          menu[m] = true;
        });
        roles.auth.uri.forEach(u => {
          uri[u] = true;
        });
        roles.auth.operation.forEach(o => {
          operations[o] = true;
        });
      });

      this.ctx.session.menu = menu;
      this.ctx.session.uri = uri;
      this.ctx.session.operations = operations;
      return;
    }

    async getAdminRole() {
      const user = this.ctx.model.RbacUser.findOne({ name: 'admin' }).populate('roles');
      this.ctx.logger.info('user', user);
      // return user;
      const menu = {};
      const uri = {};
      const operations = {};
      user.roles.forEach(roles => {
        roles.auth.menu.forEach(m => {
          menu[m] = true;
        });
        roles.auth.uri.forEach(u => {
          uri[u] = true;
        });
        roles.auth.operation.forEach(o => {
          operations[o] = true;
        });
      });
      return { menu, uri, operations };
    }

    async updateUser(userId, data) {
      await this.ctx.model.RbacUser.findOneAndUpdate({ _id: userId }, { $set: { roles: data } });
      return;
    }

    async resetPwd(userId) {
      await this.ctx.model.RbacUser.findOneAndUpdate({ _id: userId }, { $set: { passwd: cipher.md5['+']('admin;') } });
      return;
    }
  }
  return systemService;
};
